package com.pet_clinic.controller;

import com.atguigu.campus.pojo.Student;
import com.atguigu.campus.service.StudentService;
import com.atguigu.campus.utils.Result;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.github.xiaoymin.knife4j.core.util.StrUtil;
import jakarta.annotation.Resource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.HandlerMapping;

import java.util.List;

@RestController
@RequestMapping("/sms/studentController")
public class StudentController {

    @Resource
    private StudentService studentService;
    @Autowired
    private HandlerMapping resourceHandlerMapping;

    /**
     * 带条件的分页查询功能
     * @param pn 当前页码
     * @param pageSize 每页显示的记录数
     * @param student 模糊查询条件
     * @return 返回查询结果封装page对象
     */
    @GetMapping("/getStudentByOpr/{pn}/{pageSize}")
    public Result<Object> getStudents(@PathVariable("pn")Integer pn, @PathVariable("pageSize")Integer pageSize, Student student){

        String clazzName=student.getClazzName();
        String name=student.getName();
        LambdaQueryWrapper<Student> lambdaQueryWrapper= new LambdaQueryWrapper<>();
        lambdaQueryWrapper.like(StrUtil.isNotBlank(clazzName),Student::getClazzName,clazzName).like(StrUtil.isNotBlank(name),Student::getName,name).orderByDesc(Student::getId);
        Page<Student> page = studentService.page(new Page<>(pn, pageSize), lambdaQueryWrapper);

        return Result.ok(page);
    }


    /**
     *单条记录和批量删除功能
     * @param idlist 请求体中待删除的年纪id的集合（List）
     * @return
     */
    @DeleteMapping("/deleteStudent")
    public Result<Object> deleteStudents(@RequestBody List<Integer> idlist){

        //单条记录删除
        if(idlist.size()==1){
            studentService.removeById(idlist.get(0));
        }else {
            studentService.removeByIds(idlist);
        }
        return Result.ok();
    }

    /**
     * 根据判断请求体中是否存在id 进行判断是添加还是修改
     * @param student 把请求体中的JSON数据封装到实体类Student中
     * @return 返回成功
     */
    @PostMapping("/saveOrUpdateStudent")
    public Result<Object> saveOrUpdateStudent(@RequestBody Student student){

        //判断请求体中是否存在id，存在是修改，否则是添加
        Integer id = student.getId();
        if(id!=null){
            studentService.update(student,new LambdaQueryWrapper<Student>().eq(Student::getId,id));
        }else {
            studentService.save(student);
        }
        return Result.ok();
    }

    @GetMapping("/getStudents")
    public Result getStudents(){
        List<Student> list = studentService.list();
        return Result.ok(list);
    }


}
